package com.vhall.component.service.inav.impl;

import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.constant.RoomConstant;
import com.vhall.component.service.inav.WheatCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yuanzh
 * @date 2021/10/11
 */
@Slf4j
@Service
public class WheatCacheServiceImpl implements WheatCacheService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void cacheWaitingForWheat(String roomId, Integer accountId) {
        String cacheKey = RedisKey.INTERACT_WAITING_FOR_WHEAT + roomId;
        BoundZSetOperations<String, String> ops = stringRedisTemplate.boundZSetOps(cacheKey);
        ops.add(String.valueOf(accountId), System.currentTimeMillis());
        ops.expire(RoomConstant.INVITE_VALID_TIME, TimeUnit.SECONDS);
    }

    @Override
    public void removeCachedWaitingForWheat(String roomId, Integer accountId) {
        String cacheKey = RedisKey.INTERACT_WAITING_FOR_WHEAT + roomId;
        stringRedisTemplate.opsForZSet().remove(cacheKey, String.valueOf(accountId));
    }

    @Override
    public Set<Integer> listCachedWaitingForWheatAccountId(String roomId) {
        String cacheKey = RedisKey.INTERACT_WAITING_FOR_WHEAT + roomId;
        Set<String> accountIds = stringRedisTemplate.opsForZSet().range(cacheKey, 0, -1);
        if (Objects.isNull(accountIds) || accountIds.isEmpty()) {
            return Collections.emptySet();
        }
        return accountIds.stream().map(Integer::parseInt).collect(Collectors.toSet());
    }
}
